import axios, { AxiosProgressEvent } from 'axios'
import { UploadFileInfo } from 'naive-ui'

interface GlobalMinioUpload {
  file: UploadFileInfo
  id: string
  qrCode?: boolean
  callback?: Function
}

// minio文件上传
export default async function globalMinioUpload(uploadInfo: GlobalMinioUpload): Promise<any> {
  const { file, id, qrCode, callback } = uploadInfo
  const params = {
    project: 'bhzs',
    filename: file.name
  }
  return axios({
    method: 'get',
    url: `${import.meta.env.VITE_APP_MINIO_API_URL}/v1/api/minio/presignedPutObject`,
    params,
    headers: {
      'Content-Type': 'application/json',
      token: 'hsmap-oss-service-2022'
    }
  })
    .then((res) => {
      const { result } = res.data
      let headers = {
        'Content-Type': 'binary',
        token: 'hsmap-oss-service-2022'
      }
      // pdf文件的Content-Type单独处理
      if (/(?<=\.)(pdf)$/gi.test(file.name)) {
        headers = {
          'Content-Type': 'application/pdf',
          token: 'hsmap-oss-service-2022'
        }
      }
      return axios({
        method: 'put',
        url: result.url,
        data: file.file,
        headers,
        onUploadProgress: (evt: AxiosProgressEvent) => {
          console.log(typeof callback, '---', evt);
          
          if (typeof callback === 'function') {
            const progress = Math.floor((evt.loaded / evt.total) * 100)
            callback(progress, id)
            console.log('progress: ' + progress + '%')
          }
        },
      })
        .then(() => {
          const url = result.url.split('?')[0]
          //如果上传得不是二位直接抛出上传oss地址得url
          if (!qrCode) {
            return { url, name: file.name, id }
          } else {
            const formData = new FormData()
            formData.append('file', file.file)
            return axios({
              method: 'post',
              url: import.meta.env.VITE_JAVA_API_URL + '/other/qrcode/decode',
              data: formData,
              headers: {
                'Content-Type': 'multipart/form-data',
                token: ''
              }
            }).then((res) => {
              if (!res.data.result) {
                window.$message.warning('该二维码无法解析地址')
              }
              return { url, name: file.name, qrcodeUrl: res.data.result, id }
            })
          }
        })
        .catch((error) => {
          console.log('error', error)
        })
    })
    .catch((error) => {
      console.log('error', error)
    })
}
